import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import {
  List,
  Card,
  Row,
  Radio,
  Input,
  Badge,
  Button,
  Icon,
  Dropdown,
  Menu,
  Avatar,
  Modal,
  Form,
  message,
  Select,
  Table,
  Popconfirm,
  DatePicker,
  Tag,
Empty
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find'
import BuildModalTitle from '@/components/BuildModalTitle';
import using from './../../../images/using.png'
import used from './../../../images/used.png'
import heart from './../../../images/heart.png'
import zuanshi from './../../../images/zuanshi.png'
import {afterCloseModal} from '@/utils/utils';
import AddOrEditQrcode from './addOrEditQrcode'
import Masonry from 'react-masonry-component';
import request from '@/utils/request';
const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const {Search, TextArea} = Input;

@connect(({fifthG_qrcodes, loading}) => ({
  fifthG_qrcodes,
  loading: loading.models.fifthG_qrcodes,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'user_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'user_delete'}),
      showPasswordBtn: find(this.permissions, {name: 'user_default_password_edit'}),
      user_password_reset: find(this.permissions, {name: 'user_password_reset'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      containerWidth: 0,
    };
  }


  componentDidMount() {
    // window.addEventListener('resize', this.resize)
    // table.addEventListener('scroll', debounce(this.scroll,150))
    this.changeTableY()
    const {dispatch} = this.props;
    const {
      fifthG_qrcodes: {pageLoaded, scrollData},
    } = this.props;
    if (pageLoaded) {
    } else {
      const {
        fifthG_qrcodes: {searchParams},
      } = this.props;
      dispatch({
        type: 'fifthG_qrcodes/fetch',
        payload: searchParams,
        callback: ()=> {
          const {dispatch} = this.props;
          dispatch({
            type: 'applications/changeLoaded',
          })
        }
      });
    }
    const that=this;
  }

  scroll = (e)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'fifthG_qrcodes/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop
      },
    })
  }
  resize = ()=> {
    this.changeTableY()
  }
  changeTableY = ()=> {
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.qrcode-box').getBoundingClientRect().top - 10
    })
  }

  componentWillUnmount() {
    // console.log('componentWillUnmount')
    // window.removeEventListener('resize', this.resize)
    // const table=document.querySelector('.ant-table-body')
    // table.removeEventListener('scroll', debounce(this.scroll,300))
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'fifthG_qrcodes/fetch',
      payload: {
        ...values,
      },
      callback: function () {
        console.log('handleSearch callback')
        if (cb) cb()
      }
    });
  }
  handleDelete = id => {
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'fifthG_qrcodes/remove',
      payload: {id},
      callback: ()=> {
        message.success('删除二维码成功')
        const {
          fifthG_qrcodes: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  handleAdd = ()=> {
    const formValues = this.AddUser.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'fifthG_qrcodes/add',
      payload: {
        ...formValues,
        role_id: formValues.role_id ? formValues.role_id.key : '',
      },
      callback: function () {
        message.success('新建用户成功')
        that.setState({
          addModal: false,
        });
        const {
          fifthG_qrcodes: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleEdit = ()=> {
    const formValues = this.editQrcode.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'fifthG_qrcodes/edit',
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback: function () {
        message.success('修改二维码成功')
        that.setState({
          editModal: false,
        });
        const {
          fifthG_qrcodes: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
      fifthG_qrcodes: {searchParams},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'状态'}>
          {getFieldDecorator('status', {
            initialValue: searchParams.status,
          })(
            <RadioGroup>
              <RadioButton value="">全部</RadioButton>
              <RadioButton value="1">等待使用</RadioButton>
              <RadioButton value="2">使用中</RadioButton>
              <RadioButton value="3">已停用</RadioButton>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem >
          <Button type="primary" icon='search' onClick={()=> {
            const {form} = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              this.handleSearch({
                page: 1,
                per_page: this.state.per_page,
                ...fieldsValue
              })

            });
          }}>
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          <Button icon="plus" style={{marginLeft: 8}} type="primary" onClick={
            ()=> {
              this.setState({
                addModal: true
              })
            }
          }>
            添加二维码
          </Button>

        </FormItem>

      </Form>
    );
  }

  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      status:'0',
      page: 1,
      per_page: 30,
    })
  }
  handleEditStatus = (id, status)=> {
    console.log(id, status)
    let sendStatus = 0;
    if (status === 1) {
      sendStatus = -1;
    } else {
      sendStatus = 1;
    }
    const that = this;
    this.props.dispatch({
      type: 'fifthG_qrcodes/editStatus',
      payload: {
        data: {
          id,
          status: sendStatus
        }
      },
      callback: function () {
        message.success('操作成功')
        that.handleSearch({
          page: that.state.page,
          username: that.state.username,
          per_page: that.state.per_page,
        })
      }
    });
  }
  handleEditApply = ()=> {
    const formValues = this.EditApplyUser.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'fifthG_qrcodes/editApply',
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback: function () {
        message.success('修改成功')
        that.setState({
          applyModal: false,
        });
        that.handleSearch({
          page: that.state.page,
          per_page: that.state.per_page,
          username: that.state.username
        });
      }
    });
  }
  handleMenuClick = (e, record) => {
    const {dispatch} = this.props;
    const that = this
    switch (e.key) {
      case 'delete':
        dispatch({
          type: 'fifthG_qrcodes/remove',
          payload: {
            id: record.id,
          },
          callback: function () {
            message.success('删除成功')
            that.handleSearch({
              page: that.state.page,
              username: that.state.username,
              per_page: that.state.per_page,
            })
          }
        });
        break;
      case 'reset':
        dispatch({
          type: 'fifthG_qrcodes/resetPassword',
          payload: {
            id: record.id,
          },
          callback: function () {
            message.success('操作成功')
            that.handleSearch({
              page: that.state.page,
              username: that.state.username,
              per_page: that.state.per_page,
            })
          }
        });
        break;
      default:
        break;
    }
  };
  findChildFunc = (cb)=> {
    this.file=cb
  }
  handleImport=()=>{
    let file=this.file();
    const formValues =this.addQrcode.props.form.getFieldsValue();
    const that=this;
    console.log('formValues',formValues)
    if(!formValues.file){
      message.error('没有选择二维码');
      return false
    }

    var formData = new FormData();
    formData.append("file", formValues.file.file);
    formData.append("allow_use_count", formValues.allow_use_count);
    formData.append("status", formValues.status);
    formData.append("remark", formValues.remark);
    formData.append("type", '3');
    request(`/admin/qrcodes`, {
      method: 'POST',
      data: formData
    }).then((response)=> {
      console.log(response);
      if(response.status===200){
        message.success('上传二维码成功')
        that.setState({
          addModal:false
        })
        const {
          fifthG_qrcodes: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    })
  }
  render() {
    const {
      fifthG_qrcodes: {data, loading, meta, searchParams, selectedRowKeys},
    } = this.props;
    const {
      form: {getFieldDecorator},
    } = this.props;
    const masonryOptions = {};
    const imagesLoadedOptions = {background: '.my-bg-image-el'}
    return <div className="custom-card">
      <div className="table-title">二维码</div>
      <div className="table-page" style={{position: 'relative'}}>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className="qrcode-box" style={{height:this.state.tableY,overflow:'auto'}}>
          {
            loading&& <div className="loading-box"><Icon type="sync" spin style={{ fontSize: '22px', color: 'blue' }} /></div>
          }
          {
            data.length===0&& <Empty />
          }
          <Masonry
            className={'my-gallery-class'} // default ''
            elementType={'ul'} // default 'div'
            options={masonryOptions} // default {}
            disableImagesLoaded={false} // default false
            updateOnEachImageLoad={false} // default false and works only if disableImagesLoaded is false
            imagesLoadedOptions={imagesLoadedOptions} // default {}
          >
            {
              data.map((item, index)=> {
                return <div className="qrcode-item item" key={index}>
                  {
                    item.status === 2 &&
                    <img src={using} className="using" alt=""/>
                  }
                  {
                    item.status === 3 &&
                    <img src={used} className="using" alt=""/>
                  }
                  <div className="top-img">
                    <img src={item.url} alt="" className="qrcode-img"/>
                  </div>
                  <div className="use-info">
                    <div className="info-item">
                      <p><img src={heart} alt=""/>{item.current_use_count}</p>
                      <h4>已使用量</h4>
                    </div>
                    <div className="info-item">
                      <p><img src={zuanshi} alt=""/>{item.allow_use_count}</p>
                      <h4>可使用量</h4>
                    </div>
                  </div>
                  <p><span>{item.created_at}</span></p>
                  <p><span>{item.remark}</span></p>
                  <div className="img-operate">
                    <div onClick={()=>{
                      this.setState({
                        editRecord:item,
                        editModal:true
                      })
                    }
                    }>编辑</div>
                     <Popconfirm title={ '确定要删除吗?'}
                                onConfirm={(e)=> {
                                  e.stopPropagation();
                                  this.handleDelete(item.id)
                                }}>
                      <div>删除</div>
                    </Popconfirm>

                  </div>
                </div>
              })
            }
          </Masonry>

        </div>

      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{...searchParams}} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal}  modalClass={'editModal'}  title={'编辑二维码'} />}
        destroyOnClose
        visible={this.state.editModal}
        centered
        afterClose={ ()=>{
          afterCloseModal() //destroyOnClose需要
        }}
        className={'editModal'}
        onOk={this.handleEdit}
        onCancel={()=> {
          this.setState({editModal: false, editRecord: {}})
        }}
      >
        <AddOrEditQrcode
          editRecord={this.state.editRecord}
          findChildFunc={this.findChildFunc}
          wrappedComponentRef={(inst) => this.editQrcode = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal}  modalClass={'addModal'}  title={'添加二维码'} />}
        visible={this.state.addModal}
        centered
        onOk={this.handleImport}
        className={'addModal'}
        onCancel={()=> {
          this.setState({addModal: false})
        }}
      >
        <AddOrEditQrcode
          findChildFunc={this.findChildFunc}
               wrappedComponentRef={(inst) => this.addQrcode = inst}/>

      </Modal>
    </div>
  }
}

export default BasicList;
